package com.tanhua.dubbo.server.api;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.dubbo.server.enums.CommentType;
import com.tanhua.dubbo.server.pojo.*;
import com.tanhua.dubbo.server.service.SendAsyncService;
import com.tanhua.dubbo.server.vo.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.ArrayList;
import java.util.List;

@Service(version = "1.0.0")
@Slf4j
public class QuanZiApiImpl implements QuanZiApi {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private SendAsyncService sendAsyncService;
    @Autowired
    private VideoApi videoApi;

    //评论数据存储在Redis中key的前缀
    private static final String COMMENT_REDIS_KEY_PREFIX = "QUANZI_COMMENT_";

    //用户是否点赞的前缀
    private static final String COMMENT_USER_LIKE_REDIS_KEY_PREFIX = "USER_LIKE_";

    //用户是否喜欢的前缀
    private static final String COMMENT_USER_LOVE_REDIS_KEY_PREFIX = "USER_LOVE_";

    private String getCommentRedisKeyPrefix(String publishId) {
        return COMMENT_REDIS_KEY_PREFIX + publishId;
    }

    private String getCommentUserLikeRedisKeyPrefix(Long userId) {
        return COMMENT_USER_LIKE_REDIS_KEY_PREFIX + userId;
    }

    private String getCommentUserLoveRedisKeyPrefix(Long userId) {
        return COMMENT_USER_LOVE_REDIS_KEY_PREFIX + userId;
    }

    @Override

    public PageInfo<Publish> queryPublishList(Long userId, Integer page, Integer pageSize) {
        //分析：查询好友的动态，实际上查询时间线表
        PageInfo<Publish> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);
        Pageable pageable = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.desc("date")));
        Query query = new Query().with(pageable);
        List<TimeLine> timeLineList = mongoTemplate.find(query, TimeLine.class, "quanzi_time_line_" + userId);
        if (CollUtil.isEmpty(timeLineList)) {
            //没有查询到数据
            return pageInfo;
        }
        //获取时间线列表中的发布id的列表
        List<Object> ids = CollUtil.getFieldValues(timeLineList, "publishId");
        //根据动态id查询动态列表
        Query queryPublish = Query.query(Criteria.where("id").in(ids)).with(Sort.by(Sort.Order.desc("created")));
        List<Publish> publishList = mongoTemplate.find(queryPublish, Publish.class);
        pageInfo.setRecords(publishList);
        return pageInfo;
    }

    @Override
    public PageInfo<Publish> queryRecommendPublishList(Long userId, Integer page, Integer pageSize) {
        PageInfo<Publish> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);
        //查询推荐结果
        String key = "QUANZI_PUBLISH_RECOMMEND_" + userId;
        String data = redisTemplate.opsForValue().get(key);
        if (StrUtil.isEmpty(data)) {
            return pageInfo;
        }
        //查询到的id进行分页处理
        List<String> pids = StrUtil.split(data, ',');
        //计算分页
        //[0,10]
        int[] startEnd = PageUtil.transToStartEnd(page - 1, pageSize);
        int startIndex = startEnd[0];//开始
        int endIndex = Math.min(startEnd[1], pids.size());//结束
        List<Long> pidLongList = new ArrayList<>();
        for (int i = startIndex; i < endIndex; i++) {
            pidLongList.add(Long.valueOf(pids.get(i)));
        }
        if (CollUtil.isEmpty(pidLongList)) {
            //没有查询到数据
            return pageInfo;
        }
        //根据pid查询publish
        Query query = Query.query(Criteria.where("pid").in(pidLongList)).with(Sort.by(Sort.Order.desc("created")));
        List<Publish> publishList = mongoTemplate.find(query, Publish.class);
        if (CollUtil.isEmpty(publishList)) {
            //没有查询到数据
            return pageInfo;
        }
        pageInfo.setRecords(publishList);
        return pageInfo;
    }

    @Override
    public String savePublish(Publish publish, Long userId) {
        try {
            //将动态添加到发布表
            if (publish.getText() == null || publish.getUserId() == null) {
                return null;
            }
            mongoTemplate.save(publish);

            //将动态添加到相册表
            Album album = new Album();
            album.setId(ObjectId.get());
            album.setPublishId(publish.getId());
            album.setCreated(publish.getCreated());
            mongoTemplate.save(album, "quanzi_album_" + userId);


            //将动态添加到每个好友的时间线表
            TimeLine timeLine = new TimeLine();
            timeLine.setId(ObjectId.get());
            timeLine.setUserId(userId);
            timeLine.setPublishId(publish.getId());
            timeLine.setDate(publish.getCreated());
            sendAsyncService.asyncSaveTimeLine(timeLine);
        } catch (Exception e) {
            log.error("保存发布信息失败 userId" + userId);
            //mongoTemplate单节点不支持事务操作,暂时不做回滚
            return null;
        }
        return publish.getId().toHexString();
    }

    @Override
    public Publish queryPublishById(String id) {
        return mongoTemplate.findById(new ObjectId(id), Publish.class);
    }

    @Override
    public Boolean likeComment(Long userId, String publishId) {
        //判断该用户是否已经点赞，如果已经点赞就直接返回
        if (this.queryUserIsLike(userId, publishId)) {
            return false;
        }

        //保存Comment数据
        Boolean result = this.saveComment(userId, publishId, CommentType.LIKE, null);
        if (!result) {
            return false;
        }

        //修改redis中的点赞数以及是否点赞

        //修改点赞数
        String redisKey = this.getCommentRedisKeyPrefix(publishId);
        String hashKey = CommentType.LIKE.toString();
        this.redisTemplate.opsForHash().increment(redisKey, hashKey, 1);

        //用户是否点赞
        String userHashKey = this.getCommentUserLikeRedisKeyPrefix(userId);
        this.redisTemplate.opsForHash().put(redisKey, userHashKey, "1");

        return true;
    }

    @Override
    public Boolean disLikeComment(Long userId, String publishId) {
        return null;
    }

    @Override
    public Long queryLikeCount(String publishId) {
        //从Redis中命中查询，如果命中直接返回即可
        String redisKey = this.getCommentRedisKeyPrefix(publishId);
        String hashKey = CommentType.LIKE.toString();
        Object data = this.redisTemplate.opsForHash().get(redisKey, hashKey);
        if (ObjectUtil.isNotEmpty(data)) {
            return Convert.toLong(data);
        }

        //查询Mongodb
        Long count = this.queryCommentCount(publishId, CommentType.LIKE);
        //写入Redis中
        this.redisTemplate.opsForHash().put(redisKey, hashKey, String.valueOf(count));

        return count;
    }

    /**
     * 查询数量
     *
     * @param publishId
     * @param commentType
     * @return
     */
    private Long queryCommentCount(String publishId, CommentType commentType) {
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId))
                .and("commentType").is(commentType.getType())
        );
        return this.mongoTemplate.count(query, Comment.class);
    }

    @Override
    public Boolean queryUserIsLike(Long userId, String publishId) {
        //从redis中查询数据
        String redisKey = this.getCommentRedisKeyPrefix(publishId);
        String userHashKey = this.getCommentUserLikeRedisKeyPrefix(userId);
        Object data = this.redisTemplate.opsForHash().get(redisKey, userHashKey);
        if (ObjectUtil.isNotEmpty(data)) {
            return StrUtil.equals(Convert.toStr(data), "1");
        }

        //查询Mongodb，确定是否已经点赞
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId))
                .and("userId").is(userId)
                .and("commentType").is(CommentType.LIKE)
        );
        long count = this.mongoTemplate.count(query, Comment.class);
        if (count == 0) {
            return false;
        }

        //写入到redis中
        this.redisTemplate.opsForHash().put(redisKey, userHashKey, "1");

        return true;
    }

    @Override
    public boolean queryCommentType(String publishId, Long userId) {
        String commentUserLikeRedisKeyPrefix = getCommentUserLikeRedisKeyPrefix(userId);
        String hashKey = CommentType.LIKE.toString();
        Object object = redisTemplate.opsForHash().get(commentUserLikeRedisKeyPrefix, hashKey);
        if (object != null) {
            String likeCount = object.toString();
            if (likeCount.equals("1")) {
                return true;
            }
        }

        Query query = new Query();
        Criteria criteria = Criteria.where("publishId").is(new ObjectId(publishId)).and("userId").is(userId).and("commentType").is(1);
        query.addCriteria(criteria);
        List<Comment> comments = mongoTemplate.find(query, Comment.class);
        if (CollUtil.isNotEmpty(comments)) {
            return true;
        }
        return false;
    }

    @Override
    public Integer saveLiked(String publishId, Long userId) {
        Comment comment = new Comment();
        comment.setId(ObjectId.get());
        comment.setPublishId(new ObjectId(publishId));
        comment.setCommentType(1);
        comment.setUserId(userId);
        Publish publish = mongoTemplate.findById(new ObjectId(publishId), Publish.class);
        comment.setPublishUserId(publish.getUserId());
        comment.setCreated(System.currentTimeMillis());
        mongoTemplate.save(comment);

        //将Redis中的点赞评论条数自增
        String commentRedisKeyPrefix = getCommentRedisKeyPrefix(publishId);
        String hashKey = CommentType.LIKE.toString();
        redisTemplate.opsForHash().increment(commentRedisKeyPrefix, hashKey, 1);

        //将Redis中的用户已点赞设置为1
        String commentUserLikeRedisKeyPrefix = getCommentUserLikeRedisKeyPrefix(userId);
        redisTemplate.opsForHash().put(commentUserLikeRedisKeyPrefix, hashKey, "1");

        //先去Redis中读取数据
        Integer likeCount = queryRedisLikes(publishId);
        if (likeCount != null) {
            return likeCount;
        }

        //Redis中没有走数据库
        Query query = new Query();
        Criteria criteria = Criteria.where("publishId").is(new ObjectId(publishId)).and("commentType").is(1);
        query.addCriteria(criteria);
        List<Comment> comments = mongoTemplate.find(query, Comment.class);
        return comments.size();
    }

    @Override
    public Integer queryRedisLikes(String publishId) {
        String commentRedisKeyPrefix = getCommentRedisKeyPrefix(publishId);
        String hashKey = CommentType.LIKE.toString();
        Object object = redisTemplate.opsForHash().get(commentRedisKeyPrefix, hashKey);
        if (object == null) {
            return null;
        }
        return Integer.parseInt(object.toString());
    }

    @Override
    public Integer deleteLiked(String publishId, Long userId) {
        //将该点赞删除
        Query query = new Query();
        Criteria criteria = Criteria.where("publishId").is(new ObjectId(publishId)).and("userId").is(userId).and("commentType").is(1);
        query.addCriteria(criteria);
        mongoTemplate.remove(query, Comment.class);

        //将Redis中的点赞评论条数自减
        String commentRedisKeyPrefix = getCommentRedisKeyPrefix(publishId);
        String hashKey = CommentType.LIKE.toString();
        redisTemplate.opsForHash().increment(commentRedisKeyPrefix, hashKey, -1);

        //将Redis中的用户的点赞键删除
        String commentUserLikeRedisKeyPrefix = getCommentUserLikeRedisKeyPrefix(userId);
        redisTemplate.opsForHash().delete(commentUserLikeRedisKeyPrefix, hashKey);

        //先去Redis中读取数据
        Integer likeCount = queryRedisLikes(publishId);
        if (likeCount != null) {
            return likeCount;
        }

        //Redis中没有走数据库
        Query query2 = new Query();
        Criteria criteria2 = Criteria.where("publishId").is(new ObjectId(publishId)).and("commentType").is(1);
        query2.addCriteria(criteria2);
        List<Comment> comments = mongoTemplate.find(query2, Comment.class);
        return comments.size();
    }

    @Override
    public Integer loveComment(String publishId, Long userId) {
        Comment comment = new Comment();
        comment.setId(ObjectId.get());
        comment.setPublishId(new ObjectId(publishId));
        comment.setCommentType(3);
        comment.setUserId(userId);
        Publish publish = mongoTemplate.findById(new ObjectId(publishId), Publish.class);
        comment.setPublishUserId(publish.getUserId());
        comment.setCreated(System.currentTimeMillis());
        mongoTemplate.save(comment);

        //将Redis中的喜欢评论条数自增
        String commentRedisKeyPrefix = getCommentRedisKeyPrefix(publishId);
        String hashKey = CommentType.LOVE.toString();
        redisTemplate.opsForHash().increment(commentRedisKeyPrefix, hashKey, 1);

        //将Redis中的用户已喜欢设置为1
        String commentUserLoveRedisKeyPrefix = getCommentUserLoveRedisKeyPrefix(userId);
        redisTemplate.opsForHash().put(commentUserLoveRedisKeyPrefix, hashKey, "1");

        //先去Redis中读取数据
        Integer likeCount = queryLoveCount(publishId);
        if (likeCount != null) {
            return likeCount;
        }

        //Redis中没有走数据库
        Query query = new Query();
        Criteria criteria = Criteria.where("publishId").is(new ObjectId(publishId)).and("commentType").is(3);
        query.addCriteria(criteria);
        List<Comment> comments = mongoTemplate.find(query, Comment.class);
        return comments.size();
    }

    @Override
    public Integer disLoveComment(String publishId, Long userId) {
        //将该喜欢删除
        Query query = new Query();
        Criteria criteria = Criteria.where("publishId").is(new ObjectId(publishId)).and("userId").is(userId).and("commentType").is(3);
        query.addCriteria(criteria);
        mongoTemplate.remove(query, Comment.class);

        //将Redis中的喜欢评论条数自减
        String commentRedisKeyPrefix = getCommentRedisKeyPrefix(publishId);
        String hashKey = CommentType.LOVE.toString();
        redisTemplate.opsForHash().increment(commentRedisKeyPrefix, hashKey, -1);

        //将Redis中的用户的喜欢键删除
        String commentUserLoveRedisKeyPrefix = getCommentUserLoveRedisKeyPrefix(userId);
        redisTemplate.opsForHash().delete(commentUserLoveRedisKeyPrefix, hashKey);

        //先去Redis中读取数据
        Integer likeCount = queryLoveCount(publishId);
        if (likeCount != null) {
            return likeCount;
        }

        //Redis中没有走数据库
        Query query2 = new Query();
        Criteria criteria2 = Criteria.where("publishId").is(new ObjectId(publishId)).and("commentType").is(3);
        query2.addCriteria(criteria2);
        List<Comment> comments = mongoTemplate.find(query2, Comment.class);
        return comments.size();
    }

    @Override
    public Integer queryLoveCount(String publishId) {
        String commentRedisKeyPrefix = getCommentRedisKeyPrefix(publishId);
        String hashKey = CommentType.LOVE.toString();
        Object object = redisTemplate.opsForHash().get(commentRedisKeyPrefix, hashKey);
        if (object == null) {
            return null;
        }
        return Integer.parseInt(object.toString());
    }

    @Override
    public boolean queryUserIsLove(String publishId, Long userId) {
        String commentUserLoveRedisKeyPrefix = getCommentUserLoveRedisKeyPrefix(userId);
        String hashKey = CommentType.LOVE.toString();
        Object object = redisTemplate.opsForHash().get(commentUserLoveRedisKeyPrefix, hashKey);
        if (object != null) {
            String likeCount = object.toString();
            if (likeCount.equals("1")) {
                return true;
            }
        }
        Query query = new Query();
        Criteria criteria = Criteria.where("publishId").is(new ObjectId(publishId)).and("userId").is(userId).and("commentType").is(1);
        query.addCriteria(criteria);
        List<Comment> comments = mongoTemplate.find(query, Comment.class);
        if (CollUtil.isNotEmpty(comments)) {
            return true;
        }
        return false;
    }

    @Override
    public Publish queryPublish(String publishId) {
        Publish publish = mongoTemplate.findById(new ObjectId(publishId), Publish.class);
        return publish;
    }

    @Override
    public Boolean saveComment(Long userId, String publishId, String content) {
        return this.saveComment(userId, publishId, CommentType.COMMENT, content);
    }

    /**
     * 保存Comment
     *
     * @return
     */
    private Boolean saveComment(Long userId, String publishId,
                                CommentType commentType, String content) {
        try {
            Comment comment = new Comment();
            comment.setId(ObjectId.get());
            comment.setUserId(userId);
            comment.setPublishId(new ObjectId(publishId));
            // 评论类型
            comment.setCommentType(commentType.getType());
            // 内容
            comment.setContent(content);
            comment.setCreated(System.currentTimeMillis());

            Publish publish = this.queryPublish(publishId);
            if (ObjectUtil.isNotEmpty(publish)) {
                comment.setPublishUserId(publish.getUserId());
            } else {
                //查询评论
                Comment myComment = this.queryCommentById(publishId);
                if (ObjectUtil.isNotEmpty(myComment)) {
                    comment.setPublishUserId(myComment.getUserId());
                } else {
                    //查询小视频
                    Video video = videoApi.queryVideoById(publishId);
                    if (ObjectUtil.isNotEmpty(video)) {
                        comment.setPublishUserId(video.getUserId());
                    } else {
                        //其他情况,直接返回
                        return false;
                    }
                }
            }

            this.mongoTemplate.save(comment);

            return true;
        } catch (Exception e) {
            log.error("保存Comment出错~ userId = " + userId + ", publishId = " + publishId + ", commentType = " + commentType, e);
        }

        return false;
    }

    /**
     * 根据id查询Comment对象
     *
     * @param id
     * @return
     */
    private Comment queryCommentById(String id) {
        return this.mongoTemplate.findById(new ObjectId(id), Comment.class);
    }

    @Override
    public PageInfo<Comment> queryLikeCommentListByUser(Long userId, Integer page, Integer pageSize) {
        return queryCommentListByUser(userId, CommentType.LIKE, page, pageSize);
    }

    @Override
    public PageInfo<Comment> queryLoveCommentListByUser(Long userId, Integer page, Integer pageSize) {
        return queryCommentListByUser(userId, CommentType.LOVE, page, pageSize);
    }

    @Override
    public PageInfo<Comment> queryCommentListByUser(Long userId, Integer page, Integer pageSize) {
        return queryCommentListByUser(userId, CommentType.COMMENT, page, pageSize);
    }

    /**
     * 查询相册表
     *
     * @param userId
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<Publish> queryAlbumList(Long userId, Integer page, Integer pageSize) {
        PageInfo<Publish> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);
        PageRequest pageRequest = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.desc("created")));
        Query query = new Query().with(pageRequest);
        List<Album> albums = mongoTemplate.find(query, Album.class, "quanzi_album_" + userId);
        if (CollUtil.isEmpty(albums)) {
            return null;
        }
        List<Object> publishIds = CollUtil.getFieldValues(albums, "publishId");
        Query queryId = Query.query(Criteria.where("id").in(publishIds))
                .with(Sort.by(Sort.Order.desc("created")));
        List<Publish> publishList = mongoTemplate.find(queryId, Publish.class);
        pageInfo.setRecords(publishList);
        return pageInfo;
    }


    public PageInfo<Comment> queryCommentListByUser(Long userId, CommentType commentType,
                                                    Integer page, Integer pageSize) {
        PageRequest pageRequest = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.desc("created")));
        Query query = Query.query(Criteria.where("publishUserId").is(userId).and("commentType")
                .is(commentType.getType())).with(pageRequest);
        List<Comment> comments = mongoTemplate.find(query, Comment.class);
        PageInfo<Comment> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);
        pageInfo.setRecords(comments);
        return pageInfo;
    }


}